<div id="main">
	<div id="bread" class="content-block">
		<a href="/">首页</a> &gt; <?php echo $this->Html->link($serie['name'],'/books/serie/'.$serie['id']);?>
		&gt; <?php echo $this->Html->link($book["Book"]["title"],'/books/view/'.$book['Book']['id']);?>
	</div>
	<div id="book" class="content-block">
		<?php echo $this->Html->image($this->Image->thumbnail($book['Book']['id'],$book["Book"]["path"]."/cover.jpg",'210*300',100,0),array('alt'=>$book["Book"]["title"])); ?>
		<div class="book-info">
			<h1><?php echo $book['Book']['title'];?></h1>
			<span><?php echo $this->Time->format('Y-m-d',$book["Book"]["timestamp"])?>
			更新</span>
			<ul>
				<li><label>作者：</label><?php if( count($book["Authors"]) > 0 ){
				foreach( $book["Authors"] as $author){
					echo $author["name"];
				}
			}
			?></li>
				<li><label>出版社：</label><?php echo $book["Publishers"][0]["name"];?></li>
				<li><label>出版时间：</label><?php echo $this->Time->format('Y-m-d',$book["Book"]["pubdate"])?></li>
				<?php if( count($book["Identifiers"]) > 0 ){?>
				<li><label>ISBN：</label><?php echo $book["Identifiers"][0]["val"];?></li>
				<?php } ?>
				<li><label>读书笔记：</label><?php echo $stat['Stat']['note_count'];?>条</li>
				<li><label>下载次数：</label><?php echo $stat['Stat']['download_count'];?>次</li>
			</ul>
		</div>
		<div class="download-info">
			<h3>发送到Kindle:</h3>
			<div class="download-kindle">
				<input name="name" size="5" type="text" /><span>@</span>
				<select name="domain">
				<option selected="selected" value="free.kindle.com">free.kindle.com
				</option>
				<option value="kindle.com">kindle.com</option>
				<option value="iduokan.com">iduokan.com</option>
				</select> <select name="format">
				<option selected="selected" value="">下载</option>
				<?php if( count($book["Datas"])> 0 ){
					foreach( $book["Datas"] as $data ){
						if( ($data["format"] == "AZW" || $data["format"] == "MOBI"  || $data["format"] == "TXT"  || $data["format"] == "PDF") && intval($data['uncompressed_size']) <= 30000000 ){?>
				<option value="<?php echo $data['format']?>"><?php echo $data['format']?>
				</option>
				<?php		}	}}?></select>
				<p>请确认您已经将@lupinlin.com加入到允许名单 <a href="#">管理允许名单</a>
				<a id="send-to-kindle" href="#share_or_not" style="display: none;">
				发送</a></p>
			</div>
			<h3>直接下载:</h3>
			<div class="download-direct">
				<p><?php if( count($book["Datas"])> 0 ){
					foreach( $book["Datas"] as $data ){
						if( $data["format"] != "MBP" )?><span>
				<a href="#share_or_not"><?php echo $data['format']?></a>(<?php echo (int)((int)$data['uncompressed_size']/1024)?>K)</span>
				<?php
					}
				}?></p>
			</div>
		</div>
	</div>
	<div id="book-desc" class="content-block">
		<h2>书籍简介:</h2>
		<div id="desc_short">
			<?php if( isset($book["Comments"]) ){ 	$comment = $book['Comments']['text'];
	$comment = str_replace("SUMMARY:<br>","",$comment);  echo $this->Text->truncate($comment,200,array('ending'=>'...','exact'=>true,'html'=>false));}?>
		</div>
		<div id="desc_full">
			<?php if( isset($book["Comments"]) ){ 	$comment = $book['Comments']['text'];
	$comment = str_replace("SUMMARY:<br>","",$comment);  echo $comment;}?></div>
		<span id="expend_desc" class="expend">展开全部</span> </div>
	<div id="book-notes" class="content-block">
		<div id="note-form">
			<h2>分享读书笔记</h2>
			<span class="note-count">已有<strong><?php echo $stat['Stat']['note_count'];?></strong>条读书笔记</span>
			<form id="noteForm" action="/notes/add/<?php echo $book['Book']['id']?>" method="post">
				<textarea id="note" name="content">#<?php echo $book['Book']['title']?>~读书笔记#</textarea>
				<div>
					<span class="word-count">还可以输入<strong>12</strong>字</span><span><input checked="checked" name="include_url" type="checkbox" />包含本页链接</span><input class="btn-share-note" type="submit" value="发布到新浪微博" /></div>
			</form>
		</div>
		<ul class="note-list">
			<?php foreach( $notes as $note ):?>
			<li id="note_<?php echo $note['Note']['status']?>">
			<p>
			<a class="author-name" href="http://weibo.com/<?php echo $note['user']['remoteid']; ?>" target="_blank">
			<?php echo $note['user']['name']; ?></a>:<?php echo $note['Note']['content'] ?></p>
			<a href="http://weibo.com/<?php echo $note['user']['remoteid']; ?>" target="_blank">
			<?php echo $this->Html->image($note['user']['avatar_url'],array('alt'=>$note['user']['name'],'class'=>'user-avatar')); ?>
			</a>
			<div class="note-bottom">
				<span class="note-time">发表于 <?php echo $this->Time->format('Y-m-d',$note["Note"]["timestamp"])?>
				</span>
				<a class="note-retweet" href="http://api.t.sina.com.cn/<?php echo $note['user']['remoteid']; ?>/statuses/<?php echo $note['Note']['status']; ?>" target="_blank">
				转发(<em>0</em>)</a>
				<a class="note-comment" href="http://api.t.sina.com.cn/<?php echo $note['user']['remoteid']; ?>/statuses/<?php echo $note['Note']['status']; ?>" target="_blank">
				评论(<em>0</em>)</a></div>
			</li>
			<?php endforeach; ?>
		</ul>
		<div class="load-more">
			加载更多...</div>
	</div>
	<div id="side">
	</div>
	<div style="display: none">
		<div id="share_or_not">
			<p class="download-status">书籍下载中...</p>
			<h2>通过新浪微博承诺:</h2>
			<form action="/books/download/<?php echo $book['Book']['id']?>" class="download-form" method="post" target="_blank">
				<textarea id="share_text" name="share_text">我刚刚下载了《#<?php echo $book['Book']['title']?>#》,我计划在#一周内#读完这本书. 在读的过程中, 我会通过微博分享我的读书笔记, 欢迎监督. </textarea>
				<div class="share_tool">
					<input id="book_format" name="format" type="hidden" />
					<input id="kindle_mail" name="kindle_mail" type="hidden" />
					<input id="weibo_no" name="submit" type="submit" value="下载但不承诺" /><input id="weibo_yes" name="submit" type="submit" value="承诺并分享" />
				</div>
			</form>
		</div>
	</div>
</div>
<script language="javascript" type="text/javascript">
	function startDownload(item){
		$('#book_format').val($(item).text());
		$('.download-form').attr('action','/books/download/<?php echo $book['Book']['id']?>');
		$('.download-status').text('书籍下载中...');
		$('.download-form').unbind('submit');
	}


$(document).ready(function(){

	$('select[name="format"]').change( function(){
		if( $(this).val() == '' ) return;
		if( $('input[name="name"]').val() == '' )
		{
			alert('请输入账户名');
			return;
		}
		
			$('#book_format').val($(this).val());
			$('#kindle_mail').val($('input[name="name"]').val()+"@"+$('select[name="domain"]').val());
			$('.download-form').attr('action','/books/send_to_kindle/<?php echo $book['Book']['id']?>?t='+Date.parse(new Date()));
			$('.download-status').text('您选择的书籍将在10分钟内发送到您的Kindle中, 如果没有收到, 请检查您是否将@lupinlin.com添加到你的接收列表中.');
			$('.download-kindle #send-to-kindle').trigger('click');
			
			$('.download-form').ajaxForm({dataType:'json',success:function(data){
				if( data.success )
					alert( data.msg );
				else{
					switch( data.msg ){
						case 'NO_LOGIN':
							if( confirm( '请先使用新浪微博账号登录' ) ){ window.location.href = "/users/sina_login"; };
							break;
						default:
							alert(data.msg);
							break;
					}
				}
			}});
			
	} );

	$('#expend_desc').click(function(){
		if( $('#desc_full').css('display') == 'none' ){
			$('#desc_full').show();
			$('#desc_short').hide();
			$('#expend_desc').text('收起');
		}else{
			$('#desc_full').hide();
			$('#desc_short').show();
			$('#expend_desc').text('展开全部');
		}
	});
	
	var bookId = 105;
		
	$(".download-direct a").fancybox({
		'hideOnContentClick': false,
		'hideOnoverlayClick':false,
		'titleShow':true,
		'onStart':startDownload
	});
	
	$(".download-kindle #send-to-kindle").fancybox({
		'hideOnContentClick': false,
		'hideOnoverlayClick':false,
		'titleShow':true
	});

	
	
	$('#weibo_yes,#weibo_no').click(function(){
		$.fancybox.close();
	});	
	
	var lastNote = "";
	$('#note').bind('keyup',function(eventObject){
		
		remainCount= 140 - ($(this).val().replace(/[^\x00-\xff]/g,"**").length)/2;
		
		if( remainCount < 0 )
		{
			$(this).text(lastNote);
			return false;
		}
		lastNote = $(this).text();
		$('span.word-count strong').text( remainCount );
	});
	
	var option = {
		dataType : 'json',
		success :function(data) { 
		if( data.success ){
			item = data.note;
			data_array = {'table':{'remoteid':data.note.user.remoteid, 'name':item.user.name, 'avatar_url':item.user.avatar_url, 'content':item.Note.content,'status':item.Note.status,'timestamp':item.Note.timestamp}};
			
			$('.note-list').setTemplateURL('/files/note_template.htm');
			
			$('.note-list').prependTemplate({'table':data_array});
			
			updateNoteCounts(item.Note.status);

			alert( "发布成功" );
		}
		else
			alert(data.msg);
    }
	};
	$('#noteForm').ajaxForm(option); 
    
   sids = '';
   $('.note-list li').each(function(i,item){
		sids += $(item).attr('id').split('_')[1]+",";
   } );
   if( sids.length > 0 )
   		sids = sids.substring(0,sids.length-1 );
   	//alert($sids);
	
	updateNoteCounts(sids);
	   
   if($('.note-list li').length == 10 ){
   $('.load-more').click(function(){
   		$.getJSON("/notes/page/<?php echo $book['Book']['id']?>/"+$('.note-list li').length, function( data ){
   			data_array = [];
   			ids = '';
			$.each(data, function(i,item){
				ids += item.Note.status+",";
				data_array[data_array.length]={'remoteid':item.user.remoteid, 'name':item.user.name, 'avatar_url':item.user.avatar_url, 'content':item.Note.content,'status':item.Note.status,'timestamp':item.Note.timestamp}
			} );
			
			if( data_array.length < 10 )
				$('.load-more').hide();

			$('.note-list').setTemplateURL('/files/note_template.htm');
			
			$('.note-list').appendTemplate({'table':data_array});
			
			if( ids.length > 0 )
				ids = ids.substring(0,ids.length-1);
				
			updateNoteCounts(ids);
   		} );
   } );
    } else{
    	$('.load-more').hide();
    }
});

jQuery.fn.appendTemplate = function(d, param) {
		return jQuery(this).each(function() {
			var t = jQuery.getTemplate(this);
			if(t === undefined) {
				if(Template.DEBUG_MODE)
					throw new Error('jTemplates: Template is not defined.');
				else
					return;
			}
			jQuery.data(this, 'jTemplateSID', jQuery.data(this, 'jTemplateSID') + 1);
			jQuery(this).append(t.get(d, param, this, 0));
		});
	};
	
jQuery.fn.prependTemplate = function(d, param) {
		return jQuery(this).each(function() {
			var t = jQuery.getTemplate(this);
			if(t === undefined) {
				if(Template.DEBUG_MODE)
					throw new Error('jTemplates: Template is not defined.');
				else
					return;
			}
			jQuery.data(this, 'jTemplateSID', jQuery.data(this, 'jTemplateSID') + 1);
			jQuery(this).prepend(t.get(d, param, this, 0));
		});
	};

	
function updateNoteCounts(sids){
   $.getJSON("/notes/counts/"+sids, function(data){
   		$.each(data,function(i,item){
   			$('#note_'+item.id+' .note-retweet em').text(item.rt);
   			$('#note_'+item.id+' .note-comment em').text(item.comments);
   		} );
   } );

}
</script>
